﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OnLineExam.Model;
using OnLineExam.BLL;
using System.Web.Security;

namespace OnLineExam.Web
{
    /// <summary>
    /// LoginHandler 的摘要说明
    /// </summary>
    public class LoginHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            string uname =context. Request.Params["txtUserName"];
            string upass = context.Request.Params["txtUserPass"];
            string pwdMd5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(upass, "MD5").ToString();

            Users u = new Users();
            u.UserID = uname;
            u.UserPwd = pwdMd5;
            bool success = UserManager.Login(ref u);
            if (success)
            {
                Role user = new Role();
                //string userId = User.Identity.Name;
                user.RoleName = RoleManager.GetRoleName(uname);
                switch (user.RoleName)
                {
                    case "管理员":
                        UserInfo(uname, "管理员");
                       context. Response.Write("管理员");
                         
                        break;
                    case "教师":
                        UserInfo(uname, "教师");
                        context.Response.Write("教师");
                         
                        break;
                    case "学生":
                        context.Response.Write("请使用域账号登陆");
                        
                        break;
                    default:
                        break;
                }
            }
            else
            {
                context.Response.Write("用户名或密码有误，请重试！");
            }
        }

        void UserInfo(string username, string userinfo)
        {
            // FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(username, true, 60);
            FormsAuthenticationTicket t1 = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddHours(2), false, userinfo);
            string encryptedTicket = FormsAuthentication.Encrypt(t1);//加密
            HttpCookie c1 = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            c1.Expires = t1.Expiration;
           HttpContext.Current. Response.Cookies.Add(c1);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}